//
//  NSString+regexp.m
//  storeapp
//
//  Created by huangyi on 13-1-29.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "NSString+regexp.h"

@implementation NSString (regexp)

-(NSArray*)regexp:(NSString*)pattern{
    NSError *error=nil;
    NSRegularExpression *exp=[NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    if (error) {
        NSLog(@"%@",error.description);
        return nil;
    }
    NSArray *match=[exp matchesInString:self options:NSMatchingReportCompletion range:NSMakeRange(0, self.length)];
    NSMutableArray *strings=[NSMutableArray array];;
    if (match.count) {
        for (NSTextCheckingResult *result in match) {
            NSString *piece=[self substringWithRange:result.range];
            [strings addObject:piece];
        }
    }
    return strings;
}
-(NSString*)regexpfind:(NSString*)pattern{
    NSArray *array=[self regexp:pattern];
    NSString *find=nil;
    if (array.count) {
        find=array[0];
    }
    return find;
}

-(NSString*)regexp:(NSString*)pattern replace:(NSString*)str{
    NSError *error=nil;
    NSRegularExpression *exp=[NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    if (error) {
        NSLog(@"%@",error.description);
        return nil;
    }
    NSMutableString *replace=[NSMutableString stringWithString:self];
    int count=[exp replaceMatchesInString:replace options:NSMatchingReportCompletion range:NSMakeRange(0, self.length) withTemplate:str];
    return count?replace:nil;
}

-(BOOL)contains:(NSString*)pattern{
    BOOL found=NO;
    NSRange range=[self rangeOfString:pattern];
    if (range.length>0) {
        found=YES;
    }
    return found;
}

@end
